<?php

/**
 * 后台登录
 * User: Administrator
 * Date: 2019/5/24
 * Time: 11:48
 */

namespace PKApp\Member;

use PKApp\Log\Classes\TraitLog;
use PKApp\Member\Classes\TraitAuth;
use PKApp\Member\Classes\TraitMember;
use PKCommon\TraitDingTalk;
use PKFrame\Controller;
use PKFrame\DataHandler\Auth;

class AdminLogin extends Controller
{

    use TraitMember, TraitLog, TraitDingTalk, TraitAuth;

    private $_login_un, $_login_pwd, $_login_ip;

    public function Main()
    {
        $params = [
            'code' => Auth::Base64Encode(request()->session(), true, 'PKCMS@' . request()->domain())
        ];
        $this->view()->SetTplParamList($params)->Display('admin_login');
    }

    public function Api()
    {
        $this->_checkPost();
        $res = $this->serviceByUser()->CheckLogin($this->_login_un, $this->_login_pwd, 'userName',true);
        if (is_string($res)) {
            $this->writeLogByLogin($this->_login_un, 'login_fail', language($res));
            $this->_cache();
            $this->noticeByJson($res);
        } else {
            $this->checkLastLogin($this->_login_un) ?: $this->dingOfLogin($this->_login_un, language('Fail_loginSizeByMax'));
            $this->checkFunctionTime() ?: $this->dingOfLogin($this->_login_un, language('TipsLogin_time'));
        }
        unset($res['encrypt']);
        $this->writeLogByLogin($this->_login_un, 'login_success');
        $result = [];
        if (array_key_exists('groupId', $res)) {
            $group = $this->serviceByGroup()->interface_getEntityById($res['groupId'], ['powerByAction']);
            if (is_array($group) && array_key_exists('powerByAction', $group)) {
                $result['powerByAction'] = $group['powerByAction'];
                $result['groupName'] = $group['name'];
            }
        } else {
            $this->noticeByJson('Group_IdEmpty');
        }
        $result = array_merge($res, $result);
        $this->_session($result);
        $this->json($result);
    }

    public function Out()
    {
        \request()->session(SESSION_AdminKey, null, true);
        $this->redirect(self::ToMeUrl('member/adminLogin'));
    }

    private function _cache()
    {
        $log_file = $this->_login_ip . '.txt';
        $log_dir = 'Login';
        $log_ip = cache()->Tmp()->Read($log_file, $log_dir);
        if (empty($log_ip)) {
            $log_ip = [TIMESTAMP];
        } else {
            $log_ip = unserialize($log_ip);
            array_push($log_ip, TIMESTAMP);
        }
//        print_r($log_ip);
        cache()->Tmp()->Write($log_file, serialize($log_ip), $log_dir);
        $count_size = count($log_ip);
        if ($count_size >= 3) {
            $this->dingOfLogin($this->_login_un, language('Fail_loginSizeByMax'));
            blackListIP()->WriteNewIP();
        } else {
            if ($this->isLowLevelOfPassword($this->_login_pwd)) {
                $this->dingOfLogin($this->_login_pwd, language('FailLogin_LowLevelOfPassword'));
                blackListIP()->WriteNewIP();
            }
        }
    }

    private function _checkPost()
    {
        $this->_login_ip = request()->GuestIP();
        $this->_login_un = $this->checkPostFieldIsEmpty('login', 'Empty_userName');
        $this->_login_pwd = $this->checkPostFieldIsEmpty('password', 'Empty_userPwd');
        $code = $this->checkPostFieldIsEmpty('code', 'Empty_code');
        $session_id = Auth::Base64Encode($code, false, 'PKCMS@' . request()->domain());
        if (empty($session_id) || $session_id != request()->session()) {
            $this->_cache();
            $this->noticeByJson('Err_code');
        }
    }

    private function _session($userInfo)
    {
        $admin = [
            'siteId' => $userInfo['siteIdByAdmin'], 'userId' => $userInfo['id'],
            'userName' => $userInfo['userName'], 'groupId' => $userInfo['groupId'],
            'powerByAction' => $userInfo['powerByAction'],
        ];
        \request()->session(SESSION_AdminKey, $admin);
    }
}
